window.onload = function () {
    if (window.top != window.self) {
        window.top.location = 'login.html'
    }
}

// var dynamicLoading = {
//   css: function (path) {
//     if (!path || path.length === 0) {
//       throw new Error('argument "path" is required !');
//     }
//     var head = document.getElementsByTagName('head')[0];
//     var link = document.createElement('link');
//     link.href = path;
//     link.rel = 'stylesheet';
//     link.type = 'text/css';
//     head.appendChild(link);
//   },
//   js: function (path) {
//     if (!path || path.length === 0) {
//       throw new Error('argument "path" is required !');
//     }
//     var head = document.getElementsByTagName('head')[0];
//     var script = document.createElement('script');
//     script.src = path;
//     script.type = 'text/javascript';
//     head.appendChild(script);
//   }
// }


$(function () {

    // 设置备案年份
    $('#year').html(new Date().getFullYear())

    var msgErrorUserPassWd = "&nbsp;&nbsp;用户名或密码错误!";
    var msgEmptyUser = "&nbsp;&nbsp;请输入账号!";
    var msgEmptyPassWd = "&nbsp;&nbsp;请输入密码!";
    var msgShortPassWd = "&nbsp;&nbsp;密码长度应大于4位!";
    var msgEmptyAuthCode = "&nbsp;&nbsp;请输入验证码!";
    var msgErrorAuthCode = "&nbsp;&nbsp;验证码错误!";

    /*
   获取用户名和密码cookies
   added by lyg  @2015-12-29, remember username and password
    */
    var cookieName_remember = "YH_LOGIN_REMEMBER",
        cookieName_username = "YH_LOGIN_USER_NAME",
        cookieName_password = "YH_LOGIN_PASSWORD";


    // added by lvj @version 3.2 @2013-7-25, set input from cookie
    function setUsernameFromCookie() {
        var j_username = $.cookie("J_USERNAME");
        if ($.trim(j_username)) {
            $("#j_username").val(j_username);
        }
    }

    /**
     * 显示消息
     */
    function showMessage() {
        if (getQueryString("authentication_error") == 1) {
            showErrorMessage(msgErrorUserPassWd, 'j_password', 'j_password');
            document.getElementById('j_password').focus();
            document.getElementById('j_password').select();
        }
    }

    //得到Cookie信息
    function getUserInfoByCookie() {
        var _remember = getCookie(cookieName_remember),
            _username = getCookie(cookieName_username) || "",
            _password = getCookie(cookieName_password) || ""
        if (_remember != null && !_remember.toString().isnullorempty()) {
            $('#j_username').val(_username);
            $('#j_password').val(_password);
            $('#ck_remember')[0].checked = true;
        }
    }

    function loginFocus() {
        document.getElementById('j_username').focus();
        //myReload();
    }

    function errorMessage() {
        if (location.href.indexOf("?login_error=true") != -1) {
            var message = document.getElementById("j_message");
            message.innerHTML = "&nbsp;&nbsp;用户名或密码错误!";
            message.style.display = "";
            document.getElementById('j_username').focus();
            document.getElementById('j_username').select();
        }
    }

    $("input").placeholder({
        labelMode: true,
        labelAlpha: true,

        labelStyle: {
            margin: "8px 0 0 2px",
            fontSize: "14px"
        }
    });
    $(".remember-wrap").hover(function () {
        $(".remember-tip").show()
    }, function () {
        $(".remember-tip").hide()
    });
    $("#SubmitButton").click(function () {
        checkForm(this.form);
    });

    /**
     * [广告宣传页初始化]
     * @return {[type]} [description]
     */
    function initTheme(addata) {
        //定义广告数据
        var _index = 0;
        var adlength = addata.length;
        changePic(addata[_index]);
        if (adlength == 1) {
            $(".theme-ctr").hide();
        }
        ;
        autoNext();

        function autoNext() {
            gt = setTimeout(function () {
                goNext();
            }, 5000)
        };

        function goNext() {
            var data = {};
            if (_index < adlength - 1) {
                data = addata[_index + 1];
                _index++;
            } else {
                data = addata[0];
                _index = 0;
            }
            ;
            clearTimeout(gt);
            changePic(data);
            autoNext();
        };

        function goPrev() {
            var data = {};
            if (_index > 0) {
                data = addata[_index - 1];
                _index--;
            } else {
                data = addata[adlength - 1];
                _index = adlength - 1;
            }
            ;
            //console.log(_index)
            clearTimeout(gt);
            changePic(data);
            autoNext();
        }

        $("#Js_right").on("click", goNext);
        $("#Js_left").on("click", goPrev);

        function changePic(data) {
            var dataobj = data;
            $(".theme-wrap").css("background-image", "url(" + dataobj.src + ")");
            $(".theme-wrap .link").attr("href", dataobj.url);
            $("#container-bg").css("background-color", dataobj.bgcolor);
        }
    };

   /* function logoutSecurity(curls) {
        curls = curls.split(',');
        $.each(curls,function(index,value){
            var curl = "//" + value+ "/security_logout";
            $.ajax({
                type: "GET",
                cache: false,
                url: curl,
                dataType: "jsonp",
                jsonp: "callback"
            });
        });
    };*/
    document.target = "_top";
    /*
            $("#SubmitButton").click(function(){
                check(this.form);
            }); */

    $('#ResetButton').click(function () {
        $("#j_username,#j_password,#checkCode").val("")
    })

    function urlChange(obj) {
        url = obj.value;
    }

    /**
     *
     * @param msg  消息字符串
     *
     */
    function showErrorMessage(msg) {
        var message = document.getElementById("j_message");
        message.innerHTML = msg;
        message.style.display = "";

    }

    function getQueryString(name) {
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
        var r = window.location.search.substr(1).match(reg);
        if (r != null) return unescape(r[2]);
        return null;
    }

    function checkForm(form, url) {
        var username = form.j_username.value;
        var password = form.j_password.value;
        var authCode = form.checkCode.value;
        var message = document.getElementById("j_message");
        if (username == "") {
            message.innerHTML = msgEmptyUser;//"&nbsp;&nbsp;请输入操作员号!";
            message.style.display = "";
            document.getElementById('j_username').focus();
            document.getElementById('j_username').select();
            return false;
        } else if (password == "") {
            message.innerHTML = msgEmptyPassWd;//"&nbsp;&nbsp;请输入密码!";
            message.style.display = "";
            document.getElementById('j_password').focus();
            document.getElementById('j_password').select();
            return false;
        } else if (password.length < 4) {
            message.innerHTML = msgShortPassWd;//"&nbsp;&nbsp;密码长度应大于4位!";
            message.style.display = "";
            document.getElementById('j_password').focus();
            document.getElementById('j_password').select();
            return false
        } else if (authCode == "") {
            message.innerHTML = msgEmptyAuthCode;//"&nbsp;&nbsp;请输入验证码!";
            message.style.display = "";
            document.getElementById('checkCode').focus();
            document.getElementById('checkCode').select();
            return false;
        } else if (authCode != "") {
            $.get('https://www.cnpdx.com/checkAuthCode?pAuthCode=' + authCode + '&nocache=' + new Date().getTime(),
                function (result) {
                    setUsernameIntoCookie();
                    if (result == '0') {
                        myReload();
                        message.innerHTML = msgErrorAuthCode;//"&nbsp;&nbsp;验证码错误!";
                        message.style.display = "";
                        $('#checkCode').focus();
                        $('#checkCode').select();
                        document.getElementById("SubmitButton").disabled = false;
                        $('#SubmitButton').attr('disabled', false);
                        return false;
                    } else {
                        setUserInfoByCookie();
                        $.post("/pctpOs/loginApi", $("#loginForm").serialize(), function (data, status, xhr) {
                            if (data.status == 200) {
                                  var callBackUrl = $.cookie("callBackUrl");
                                  if (callBackUrl){
                                      $.cookie("callBackUrl",'', { expires: -1 ,path: '/',domain:cookiesScope});
                                  }else {
                                      callBackUrl = data.redirectUrl;
                                  }
                                  if(window.location.search) {
                                        const urlParams = new URLSearchParams(window.location.search)
                                        const by = decodeURIComponent(urlParams.get('by'));
                                        const to = decodeURIComponent(urlParams.get('from'))
                                        const isbn = urlParams.get('isbn')
                                        const serialNo = urlParams.get('serialNo')
                                        window.location.href = `${to}?username=${$("#loginForm input[name='j_username']").val()}&phpsessid=${data.phpsessid}&by=${by}&isbn=${isbn}&serialNo=${serialNo}`
                                  }
                                  // window.location.href = callBackUrl;
                            } else {
                                console.log(data.msg)
                              // 排除易采购账号
                              if(data.mustUpdate == undefined){
                                showErrorMessage(data.msg);
                                document.getElementById('j_password').focus();
                                document.getElementById('j_password').select();
                              }else{
                                // 非易采购账号走提示模式
                                askModal(data.mustUpdate, data.msgType, data.msg, data.redirectUrl)
                              }
                            }
                        });
                        return true;
                    }
                });
        }
    };

    // 可继续使用询问框
    /**
     *
     * @param {Boolean} must   // 必须处理
     * @param {Array} showtype // 后续要弹出的类型【“UPDATE_MOBILE”-绑定手机，“UPDATE_PASSWORD”-修改密码】
     * @param {String} msg     // 原因
     * @param {String} url          // 继续使用跳转的url
     */
    function askModal(must ,showtype, msg, url) {
      // 需要绑定手机和密码的标记
      var m = false, c = false
      must = JSON.parse(must)
      m = showtype && showtype.length && showtype.indexOf('UPDATE_MOBILE')!= -1 ? true : false
      p = showtype && showtype.length && showtype.indexOf('UPDATE_PASSWORD')!= -1 ? true : false

      var d;
      if(!must){
        // 非必须处理可以继续使用
        d = dialog({
          title: '提示',
          width: 460,
          autofocus: false,
          content: msg,
          okValue: '确定修改',
          ok: function () {
            if(m){
              bindMobilePhone(p, url)
            }else if(!m && p){
              changePassword()
            }
          },
          cancelValue: '继续使用',
          cancel: function () {
            $.ajax({
              url: "/service/user/updatePasswordLastUpdateTime",
              type: "post",
              data: {
                userName: $('input[name="j_username"]').val(),
                password: $('input[name="j_password"]').val()
              },
              success: function (res) {
                var callBackUrl = $.cookie("callBackUrl");
                if (callBackUrl){
                    $.cookie("callBackUrl",'', { expires: -1 ,path: '/',domain:cookiesScope});
                }else {
                    callBackUrl = url;
                }
                if(url){
                  window.location.href = callBackUrl;
                }
              },
              error: function (err) {
                showMsg('系统错误，请稍后重试')
              }
            })
            return false
          }
        });
      }else{
        // 必须处理
        d = dialog({
          title: '提示',
          width: 460,
          autofocus: false,
          content: msg,
          okValue: '确定修改',
          cancel: false,
          ok: function () {
            if(m){
              bindMobilePhone(p, url)
            }else if(!m && p){
                 //修改密码
                 window.location.href='/updatePasswordPage?returntype=1'
            //   changePassword()
            }
            // return false;
          }
        });
      }
      d.showModal();
    }

    /**
     * 登录时绑定手机号
     * @param {Boolean} needChangePassword 是否需要继续修改密码流程 [true/false]
     * @param {String} url 跳转路径
     */
    function bindMobilePhone (needChangePassword, url) {
      var d2 = dialog({
        title: '绑定手机号',
        width: 420,
        autofocus: false,
        content: '' +
          '<form novalidate="" class="psw-form">' +
          '  <div class="input-box">' +
          '      <div class="input-item-wrap">' +
          '          <label class="input-label" for=""><span class="red">*</span> 绑定手机</label>' +
          '          <div class="item-group">' +
          '              <input class="input-item" id="mobile" type="text" name="mobile">'+
          '              <button class="btn get-verify" type="button">获取验证码</button>' +
          '          </div>' +
          '          <span class="red err-hint"></span>' +
          '      </div>' +
          '  </div>' +
          '  <div class="input-box">' +
          '      <div class="input-item-wrap">' +
          '          <label class="input-label" for=""><span class="red">*</span> 验证码</label>' +
          '          <div class="item-group">' +
          '              <input class="input-item" type="text" name="verifyCode">' +
          '          </div>' +
          '          <span class="red err-hint"></span>' +
          '      </div>' +
          '  </div>' +
          '</form>',
        okValue: '确定',
        ok: function () {
          confirmBindMobilePhone(d2, needChangePassword, url)
          return false
        },
        cancelValue: '取消',
        cancel: function () {
          $('#j_password').val('');
          $('#checkCode').val('');
          myReload()
        }
      });
      d2.showModal();

      $('.get-verify').off('click').on('click', function (e) {
        var flag = validateMobile();
        if (!flag) return false;
        getVerify()
      })

      $('#mobile').off('blur').on('blur', function(){
        validateMobile()
      })
    }
    // 确认绑定手机号
    function confirmBindMobilePhone(dialog, needChangePassword, url) {
      var flag = validateMobile() && validateVcode();
      if (!flag ) return;
      // 提交数据
      var data = {
        username: $('input[name="j_username"]').val(),
        mobile: $('input[name="mobile"]').val(),
        prePassword: $('#j_password').val(),
        verifyCode: $('input[name="verifyCode"]').val()
      }
      $.ajax({
          url: "/service/user/bindingMobileFromLogin",
          type: "post",
          data: data,
          success: function (res) {
              if (res.status != 200) {
                  // showMsg(res.msg)
                  $('input[name="verifyCode"]').parent().siblings('.err-hint').text(res.msg);
              } else {
                  dialog.close().remove();
                  if(!needChangePassword) {
                    var callBackUrl = $.cookie("callBackUrl");
                    if (callBackUrl){
                        $.cookie("callBackUrl",'', { expires: -1 ,path: '/',domain:cookiesScope});
                    }else {
                        callBackUrl = url;
                    }
                    if(url){
                      window.location.href = callBackUrl;
                    }
                  }else{
                    changePassword(url)
                  }

              }
          },
          error: function (err) {
              // showMsg('系统错误，请稍后重试')
              $('input[name="mobile"]').addClass('error').parent().siblings('.err-hint').text('系统错误，请稍后重试');
          }
      })
    }

    // 需要-修改密码
    function changePassword (url) {
      var d2 = dialog({
        title: '修改密码',
        width: 420,
        autofocus: false,
        content: '' +
          '<form novalidate="" class="psw-form">' +
          '  <div class="input-box">' +
          '      <div class="input-item-wrap">' +
          '          <label class="input-label" for=""> 用户名</label>' +
          '          <div class="item-group">' +
          '              <input class="input-item" type="text" name="username" disabled>' +
          '          </div>' +
          '          <span class="red err-hint"></span>' +
          '      </div>' +
          '  </div>' +
          '  <div class="input-box">' +
          '      <div class="input-item-wrap">' +
          '          <label class="input-label" for=""><span class="red">*</span> 原密码</label>' +
          '          <div class="item-group">' +
          '              <input class="input-item" type="password" name="oldPassword">' +
          '          </div>' +
          '          <span class="red err-hint"></span>' +
          '      </div>' +
          '  </div>' +
          '  <div class="input-box">' +
          '      <div class="input-item-wrap">' +
          '          <label class="input-label" for=""><span class="red">*</span> 新密码</label>' +
          '          <div class="item-group">' +
          '              <input class="input-item" type="password" name="newPassword">' +
          '          </div>' +
          '          <span class="red err-hint"></span>' +
          '      </div>' +
          '  </div>' +
          '  <div class="input-box">' +
          '      <div class="input-item-wrap">' +
          '          <label class="input-label" for=""><span class="red">*</span> 确认密码</label>' +
          '          <div class="item-group">' +
          '              <input class="input-item" type="password" name="confirmPassword">' +
          '          </div>' +
          '          <span class="red err-hint"></span>' +
          '      </div>' +
          '  </div>' +
          '</form>',
        okValue: '确定',
        ok: function () {
          confirmChangePassword(d2, url)
          return false
        },
        cancelValue: '取消',
        cancel: function () {
          $('#j_password').val('');
          $('#checkCode').val('');
          myReload()
        }
      })
      d2.showModal();
      $('input[name="username"]').val($('input[name="j_username"]').val())
    }

    // 确认修改密码
    function confirmChangePassword(dialog, url) {
      var flag = validatePassword();
      if (!flag ) return;

      // 提交数据
      var data = {
        username: $('input[name="j_username"]').val(),
        prePassword: $('input[name="oldPassword"]').val(),
        newPassword: $('input[name="newPassword"]').val(),
        confirmPassword: $('input[name="confirmPassword"]').val()
      }
      $.ajax({
          url: "/service/user/updatePasswordFromLogin",
          type: "post",
          data: data,
          success: function (res) {
              if (res.status != 200) {
                  // showMsg()
                  $('input[name="oldPassword"]').addClass('error').parent().siblings('.err-hint').text(res.msg);
              } else {
                  dialog.close().remove();
                  showMsg("密码修改成功，请重新登录")

                  $('#j_password').val('');
                  $('#checkCode').val('');
                  myReload()
              }
          },
          error: function (err) {
              // showMsg('系统错误，请稍后重试')
              $('input[name="oldPassword"]').addClass('error').parent().siblings('.err-hint').text('系统错误，请稍后重试');
          }
      })
    }

    // 验证密码
    function validatePassword() {
      var psw = $('input[name="newPassword"]').val();
      var confirmPsw = $('input[name="confirmPassword"]').val();
      var reg = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[^]{8,20}$/;
      if (!reg.test(psw)) {
          $('input[name="newPassword"]').addClass('error').parent().siblings('.err-hint').text("必须同时包含数字、大小写字母，且8-20位的组合");
      } else if (psw !== confirmPsw) {
          $('input[name="confirmPassword"]').addClass('error').parent().siblings('.err-hint').text("两次输入密码不一致，请重新输入");
      } else {
          $('input[name="newPassword"]').removeClass('error').parent().siblings('.err-hint').text("");
          $('input[name="confirmPassword"]').removeClass('error').parent().siblings('.err-hint').text("");
          return true;
      }
  }

    // 验证手机号
    function validateMobile() {
      let mobile = $('input[name="mobile"]').val();
      let isMobile = /^1[3456789]\d{9}$/;
      if (!mobile) {
          $('input[name="mobile"]').addClass('error').parent().siblings('.err-hint').text("请输入手机号");
          return false;
      } else if (!isMobile.test(mobile)) {
          $('input[name="mobile"]').addClass('error').parent().siblings('.err-hint').text("手机号格式不正确");
          return false;
      } else {
          $('input[name="mobile"]').removeClass('error').parent().siblings('.err-hint').text("");
          return true;
      }
    }

    function validateVcode() {
      var vcode = $('input[name="verifyCode"]').val();
      if(!vcode) {
        $('input[name="verifyCode"]').addClass('error').parent().siblings('.err-hint').text("请输入验证码");
        return false;
      } else {
        $('input[name="verifyCode"]').removeClass('error').parent().siblings('.err-hint').text("");
        return true;
      }
    }

    // 绑定手机号-获取验证码
    function getVerify() {
      var data = {
          username: $('input[name="j_username"]').val(),
          mobile: $('input[name="mobile"]').val()
      }
      $.ajax({
          url: "/service/user/bindingMobileFromLoginSendSms",
          type: "post",
          data: data,
          success: function (res) {
              if (res.status != 200) {
                  // showMsg()
                  $('input[name="mobile"]').addClass('error').parent().siblings('.err-hint').text(res.msg);
              } else {
                  countdown(60);
              }
          },
          error: function (err) {
              // showMsg('系统错误，请稍后重试')
              $('input[name="mobile"]').addClass('error').parent().siblings('.err-hint').text('系统错误，请稍后重试');
          }
      })
    }
    // 倒计时
    function countdown(second) {
      second--;
      if (second < 0) {
          $(".get-verify").prop("disabled", false).removeClass('disabled');
          $(".get-verify").text('获取验证码');
          return;
      } else {
          $(".get-verify").prop("disabled", true).addClass('disabled');
          $(".get-verify").text(second + '秒后重发');
          setTimeout(function () {
              countdown(second);
          }, 1000);
      }
  }


    function jump(url) {
        var e = document.createElement("a");
        e.href = url;
        document.body.appendChild(e);
        e.click();
    };

    function checkCode() {
        var code = $("#checkCode").attr("value");
        code = "pAuthCode=" + code;
        $.ajax({
            type: "POST",
            url: "https://www.cnpdx.com/checkAuthCode",
            data: code,
            success: callback
        });
    };

    document.onkeydown = function (evt) {
        var evt = window.event ? window.event : evt;

        if (evt.keyCode == 13) {
            checkForm(document.forms["LoginForm"]);
        }
    };

    // added by lvj @version 3.2 @2013-7-25, set username into cookie
    function setUsernameIntoCookie() {
        var j_username = $("#j_username").val();
        if (j_username) {
            $.cookie("J_USERNAME", j_username, {path: '/', expires: 3});
        }
    };

    /*
    记录用户名和密码cookies
    added by lyg  @2015-12-29, remember username and password
     */
    function setUserInfoByCookie() {
        delCookie(cookieName_username);//删除用户名Cookie
        delCookie(cookieName_password);//删除密码Cookie
        delCookie(cookieName_remember);//删除记住用户信息
        var $remember = $('#ck_remember');
        var _username = $.trim($("#j_username").val());
        var _password = $.trim($("#j_password").val());
        if ($remember[0].checked) {
            SetCookie(cookieName_username, _username, 90);//保存到Cookie中  保存90天
            SetCookie(cookieName_password, _password, 90);
            SetCookie(cookieName_remember, $remember[0].checked, 90);
        }
    };


    $.ajax({
        url: "https://yicaigou.cnpdx.com/gd/system/json/getPosterManagement",
        type: "post",
        async:false,
        data:{
            moduleType:"LOGIN_SYS",
        },
        dataType:"jsonp",
        jsonp:"callback",
        success:function(rs){

            var addata=rs.obj;
            for ( var i = 0; i < addata.length; i++) {
                addata[i].src="https://"+gdHost+addata[i].src;

                if(!addata[i].url ||addata[i].url==='#'  ){
                    addata[i].url='javascript:;'
                }
                if(addata[i].url!=='javascript:;' && addata[i].url!=='#' ){
                    addata[i].url="https://"+staticHost+"/"+addata[i].url
                }

            }
            console.log(addata)
            initTheme(addata);
        },
        error:function () {

        }
    });

    function showMsg(msg) {
      var toaster = '<div class="toaster"><p class="hint">' + msg + '</p></div>';

      $("body").append(toaster);
      setTimeout(function () {
          $('body').find('.toaster').remove();
      }, 2000);
  }


    setUsernameFromCookie();
    // 如果有异常消息，则显示
    showMessage();
    getUserInfoByCookie();
    loginFocus();
    errorMessage();
    // logoutSecurity();
});

function myReload() {
    document.getElementById("checkImge").src = document.getElementById("checkImge").src.split("?", 2)[0] + "?nocache=" + new Date().getTime();
};
